
package com.epam.android.training.day3.task3;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Application activity which handeles storing dummy config state on changing
 * device orientation.
 * 
 * @author Anton Novikau
 */
public class ConfigurationKeeper extends Activity {

    private static final String CONFIG_FILE = "config.properties";

    private static final String AGE = "age";

    private static final String LAST_NAME = "last_name";

    private static final String FIRST_NAME = "first_name";

    private Properties config;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        config = loadConfig();
        setLabelValue(config.getProperty(FIRST_NAME), R.id.firstName);
        setLabelValue(config.getProperty(LAST_NAME), R.id.lastName);
        setLabelValue(config.getProperty(AGE), R.id.age);
    }

    /**
     * Called by the system, as part of destroying an activity due to a
     * configuration change.
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        showToastMessage(R.string.config_cached);
        return config;
    }

    private Properties loadConfig() {
        Properties config;

        // try to get last configuration state
        Object data = getLastNonConfigurationInstance();
        if (data == null) {

            // load config if is not cached yet.
            config = new Properties();
            try {
                InputStream configStream = getAssets().open(CONFIG_FILE);
                config.load(configStream);

                showToastMessage(R.string.config_loaded);
            } catch (IOException e) {
                showToastMessage(R.string.config_read_error);
            }
        } else if (data instanceof Properties) {
            // use cached config if one is present.
            config = (Properties) data;
            showToastMessage(R.string.config_restored);
        } else {

            // rise exeption if cached one has not Properties type.
            throw new IllegalStateException("Only dummy entities are supported to be restored.");
        }

        return config;
    }

    private void showToastMessage(int messageResource) {
        Toast.makeText(getApplicationContext(), messageResource, Toast.LENGTH_SHORT).show();
    }

    private void setLabelValue(String value, int labelId) {
        TextView label = (TextView) findViewById(labelId);
        label.setText(value);
    }
}
